<template>
  <div class="cart-container">
    <!-- 头部 -->
    <Header />
    
    <!-- 主体内容 -->
    <div class="main-content">
      <div class="cart-wrapper">
        <h2 class="page-title">我的购物车</h2>
        
        <!-- 购物车为空提示 -->
        <div class="empty-cart" v-if="cart.length === 0">
          <i class="el-icon-shopping-cart-2"></i>
          <p>购物车是空的，去<router-link to="/merchants">选购美食</router-link>吧</p>
        </div>
        
        <!-- 购物车内容 -->
        <div class="cart-content" v-else>
          <!-- 按商家分组展示购物车商品 -->
          <div v-for="(group, merchantId) in groupedCart" :key="merchantId" class="merchant-cart">
            <!-- 商家信息 -->
            <div class="merchant-info">
              <div class="merchant-name">{{ group.merchantName || '未知商家' }}</div>
              <el-button type="text" @click="clearMerchantCart(merchantId)" class="clear-btn">
                清空
              </el-button>
            </div>
            
            <!-- 商品列表 -->
            <div class="cart-item-list">
              <div v-for="item in group.items" :key="item.id" class="cart-item">
                <div class="item-image">
                  <img :src="item.image || 'https://via.placeholder.com/60'" :alt="item.name">
                </div>
                <div class="item-info">
                  <div class="item-name">{{ item.name }}</div>
                  <div class="item-price">¥{{ item.price }}</div>
                </div>
                <div class="item-actions">
                  <el-input-number 
                    v-model="item.quantity" 
                    :min="1" 
                    :max="99"
                    size="small"
                    @change="updateCartItemQuantity(item.id, item.quantity)">
                  </el-input-number>
                  <el-button 
                    type="danger" 
                    icon="el-icon-delete" 
                    circle
                    size="small"
                    @click="removeFromCart(item.id)">
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 商家小计 -->
            <div class="merchant-subtotal">
              <span class="subtotal-label">小计:</span>
              <span class="subtotal-value">¥{{ calculateMerchantTotal(merchantId) }}</span>
            </div>
          </div>
          
          <!-- 购物车底部 -->
          <div class="cart-footer">
            <div class="cart-total">
              <span class="total-label">总计:</span>
              <span class="total-value">¥{{ calculateTotal() }}</span>
            </div>
            <div class="cart-actions">
              <el-button type="primary" @click="goToCheckout">去结算</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 底部 -->
    <Footer />
  </div>
</template>

<script>
import Header from '@/components/Header'
import Footer from '@/components/Footer'
import { mapMutations } from 'vuex'
import { getUserCart, getUserCartDetail, updateCartItemQuantity, deleteCartItem, clearUserCartByMerchant } from '@/api/cart'

export default {
  name: 'Cart',
  components: {
    Header,
    Footer
  },
  data() {
    return {
      cart: [], // 本地购物车数据
      loading: false // 加载状态
    }
  },
  created() {
    // 获取购物车详情
    this.fetchCartData()
  },
  
  computed: {
    // 按商家分组的购物车商品
    groupedCart() {
      const groups = {}

      this.cart.forEach(item => {
        const merchantId = item.merchantId
        
        if (!groups[merchantId]) {
          groups[merchantId] = {
            merchantName: item.merchantName,
            items: []
          }
        }
        
        groups[merchantId].items.push(item)
      })
      
      return groups
    }
  },
  methods: {
    ...mapMutations(['SET_CART']),
    // 获取购物车数据
    fetchCartData() {
      this.loading = true
      const userId = this.$store.getters.currentUser.id
      getUserCartDetail(userId).then(response => {
        if (response.code == 200) {
          this.cart = response.data
          // 同步到Vuex状态
          this.SET_CART(response.data)
        } else {
          this.$message.error(response.message || '获取购物车失败')
        }
      }).catch(error => {
        console.error('获取购物车失败', error)
        this.$message.error('获取购物车失败，请稍后再试')
      }).finally(() => {
        this.loading = false
      })
    },
    // 更新购物车商品数量
    updateCartItemQuantity(id, quantity) {
      const userId = this.$store.getters.currentUser.id
      updateCartItemQuantity(id, quantity, userId).then(response => {
        if (response.code == 200) {
          // 更新成功后重新获取购物车数据
          this.fetchCartData()
          this.$message.success('数量已更新')
        } else {
          this.$message.error(response.message || '更新数量失败')
        }
      }).catch(error => {
        console.error('更新购物车数量失败', error)
        this.$message.error('更新购物车数量失败，请稍后再试')
      })
    },
    // 从购物车移除商品
    removeFromCart(id) {
      const userId = this.$store.getters.currentUser.id
      deleteCartItem(id, userId).then(response => {
        if (response.code == 200) {
          // 删除成功后重新获取购物车数据
          this.fetchCartData()
          this.$message.success('商品已从购物车移除')
        } else {
          this.$message.error(response.message || '移除商品失败')
        }
      }).catch(error => {
        console.error('移除购物车商品失败', error)
        this.$message.error('移除购物车商品失败，请稍后再试')
      })
    },
    // 清空指定商家的购物车
    clearMerchantCart(merchantId) {
      this.$confirm('确定要清空该商家的购物车吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const userId = this.$store.getters.currentUser.id
        clearUserCartByMerchant(userId, merchantId).then(response => {
          if (response.code == 200) {
            // 清空成功后重新获取购物车数据
            this.fetchCartData()
            this.$message.success('已清空购物车')
          } else {
            this.$message.error(response.message || '清空购物车失败')
          }
        }).catch(error => {
          console.error('清空购物车失败', error)
          this.$message.error('清空购物车失败，请稍后再试')
        })
      }).catch(() => {
        // 取消清空，不做任何操作
      })
    },
    // 计算指定商家的商品总价
    calculateMerchantTotal(merchantId) {
      const group = this.groupedCart[merchantId]
      if (!group) return 0
      
      return group.items.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    },
    // 计算所有商品的总价
    calculateTotal() {
      return this.cart.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0).toFixed(2)
    },
    // 前往结算页面
    goToCheckout() {
      if (this.cart.length === 0) {
        this.$message.warning('购物车为空，请先添加商品')
        return
      }
      
      this.$router.push('/checkout')
    }
  }
}
</script>

<style scoped>
.cart-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.main-content {
  flex: 1;
  padding: 30px 0;
}

.cart-wrapper {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.empty-cart {
  text-align: center;
  padding: 50px 0;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.empty-cart i {
  font-size: 60px;
  color: #909399;
  margin-bottom: 20px;
}

.empty-cart p {
  font-size: 16px;
  color: #606266;
}

.empty-cart a {
  color: #409EFF;
}

.merchant-cart {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.merchant-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
  margin-bottom: 15px;
}

.merchant-name {
  font-size: 18px;
  font-weight: bold;
}

.clear-btn {
  font-size: 14px;
  color: #F56C6C;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px dashed #eee;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 15px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-info {
  flex: 1;
}

.item-name {
  font-size: 16px;
  margin-bottom: 5px;
}

.item-price {
  font-size: 14px;
  color: #F56C6C;
  font-weight: bold;
}

.item-actions {
  display: flex;
  align-items: center;
}

.item-actions .el-button {
  margin-left: 15px;
}

.merchant-subtotal {
  text-align: right;
  padding-top: 15px;
  font-size: 16px;
}

.subtotal-value {
  color: #F56C6C;
  font-weight: bold;
  margin-left: 10px;
}

.cart-footer {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-total {
  font-size: 18px;
}

.total-value {
  color: #F56C6C;
  font-weight: bold;
  font-size: 22px;
  margin-left: 10px;
}
</style> 